<template>
	<view class="wrapper u-p-t-60">
		<view class="img u-flex u-row-center u-m-t-60">
			<u-image width="300rpx" mode="widthFix" src="@/static/image/images/logo.png" />
		</view>
		<view class="u-p-40">
			<u-form :model="form" ref="uForm" class="u-m-b-60">
				<u-form-item label-position="top" prop="phone" required border-bottom label="手机号">
					<u-input placeholder="请输入手机号" :maxlength="11" type="number" v-model="form.phone" />
				</u-form-item>
				<u-form-item label-position="top" prop="code" required border-bottom label="验证码">
					<u-input placeholder="请输入验证码" :maxlength="6" type="number" required v-model="form.code" />
					<view slot="right">
						<u-toast ref="uToast"></u-toast>
						<u-verification-code :seconds="seconds" ref="uCode"
							@change="codeChange"></u-verification-code>
						<u-button size="mini" type="primary" @tap="getCode">{{tips}}</u-button>
					</view>
				</u-form-item>
			</u-form>
			<view class="u-p-l-50 u-p-r-50">
				<u-button ripple shape="circle" type="primary" @tap="login">登录</u-button>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				form: {
					phone: '',
					code: '',
				},
				rules: {
					phone: [{
						required: true,
						message: '请输入手机号',
						trigger: ['blur', 'change']
					}, {
						validator: (rule, value, callback) => {
							return this.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						trigger: ['change', 'blur'],
					}],
					code: [{
							required: true,
							message: '请输入验证码',
							trigger: ['blur', 'change']
						},
						{
							validator: (rule, value, callback) => {
								return this.$u.test.code(value, 6)
							},
							message: '验证码格式不正确',
							trigger: ['change', 'blur'],
						}
					],
				},
				tips: '',
				// refCode: null,
				seconds: 10,
			}
		},
		onReady() {
			// 注意这里不能将一个组件赋值给data的一个变量，否则在微信小程序会
			// 造成循环引用而报错，如果你想这样做，请在非data中定义refCode变量
			// this.refCode = this.$refs.uCode;
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			codeChange(text) {
				this.tips = text;
			},
			login(){
				this.$refs.uForm.validate(valid => {
					if (valid) {
						this.$u.toast('这里验证成功，走登录接口');
					} else {
						this.$u.toast('验证失败');
					}
				});
			},
			getCode() {
				if(this.$u.test.mobile(this.form.phone) && this.form.phone){
					// 手机号输入框验证成功
					if (this.$refs.uCode.canGetCode) {
						// 模拟向后端请求验证码
						uni.showLoading({
							title: '正在获取验证码'
						})
						setTimeout(() => {
							uni.hideLoading();
							// 这里此提示会被this.start()方法中的提示覆盖
							this.$u.toast('验证码已发送');
							// 通知验证码组件内部开始倒计时
							this.$refs.uCode.start();
						}, 2000);
					} else {
						this.$u.toast('倒计时结束后再发送');
					}
				}else{
					this.$u.toast('请输入正确手机号再获取验证码');
				}
				
			},
		}
	}
</script>

<style lang="scss" scoped>
	.wrapper {
		.img {
			padding: 80rpx;
		}
	}
</style>
